package com.example.inventoryservice.controller;

import com.example.inventoryservice.actor.PersistentInventoryActor;
import com.example.inventoryservice.service.InventoryEventQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.CompletionStage;

/**
 * 库存事件查询控制器
 * 提供库存事件溯源查询的REST API
 */
@Slf4j
@RestController
@RequestMapping("/api/inventory/events")
public class InventoryEventQueryController {
    
    @Autowired
    private InventoryEventQueryService inventoryEventQueryService;
    
    /**
     * 查询指定订单的库存事件
     */
    @GetMapping("/orders/{orderId}")
    public CompletionStage<ResponseEntity<List<InventoryEventQueryService.InventoryEvent>>> getInventoryEventsForOrder(@PathVariable String orderId) {
        log.info("查询订单库存事件: {}", orderId);
        
        return inventoryEventQueryService.getInventoryEventsForOrder(orderId)
            .thenApply(events -> {
                if (events.isEmpty()) {
                    return ResponseEntity.notFound().build();
                }
                return ResponseEntity.ok(events);
            })
            .exceptionally(throwable -> {
                log.error("查询库存事件失败: {}", throwable.getMessage(), throwable);
                return ResponseEntity.internalServerError().build();
            });
    }
    
    /**
     * 重建库存状态
     */
    @GetMapping("/state")
    public CompletionStage<ResponseEntity<PersistentInventoryActor.InventoryState>> rebuildInventoryState() {
        log.info("重建库存状态");
        
        return inventoryEventQueryService.rebuildInventoryState()
            .thenApply(state -> ResponseEntity.ok(state))
            .exceptionally(throwable -> {
                log.error("重建库存状态失败: {}", throwable.getMessage(), throwable);
                return ResponseEntity.internalServerError().build();
            });
    }
    
    /**
     * 查询所有库存变更历史
     */
    @GetMapping("/changes")
    public CompletionStage<ResponseEntity<List<InventoryEventQueryService.InventoryChangeHistory>>> getAllInventoryChanges() {
        log.info("查询所有库存变更历史");
        
        return inventoryEventQueryService.getAllInventoryChanges()
            .thenApply(changes -> ResponseEntity.ok(changes))
            .exceptionally(throwable -> {
                log.error("查询库存变更历史失败: {}", throwable.getMessage(), throwable);
                return ResponseEntity.internalServerError().build();
            });
    }
}

